import MainCard from '@/ui-component/cards/MainCard'
import { getAdvisorShiftList, getAdvisorList } from '@/api/index'
import { gridSpacing, DefaultPagination, PageSizes, ButtonConfig } from '@/store/constant'
import { NameGradeCell, MoreActionButton, DatePeriodSelect } from '@/components'
import ScheduleActionButton from './ScheduleActionButton'
import { grey } from '@mui/material/colors'
import { GridRenderCellParams, GridRowsProp } from '@mui/x-data-grid'
import { DatePeriod } from '@/types/common'
import BatchScheduleButton from './BatchScheduleButton'
import { ElementType } from 'react'

const FORMATTER = 'YYYY-MM-DD'
const Schedule = () => {
  const theme = useTheme()
  const matches = useMediaQuery(theme.breakpoints.up('md'))
  const isPassed = (date: string) => dayjs(date).isBefore(dayjs(), 'day')
  const defaultStart = dayjs().subtract(1, 'week')
  const defaultEnd = dayjs().add(1, 'week')
  const [paginationModel, setPaginationModel] = useState(DefaultPagination)
  const [params, setParams] = useState<DatePeriod>({
    start_date: defaultStart.format(FORMATTER),
    end_date: defaultEnd.format(FORMATTER)
  })
  const [rows, setRows] = useState<GridRowsProp>([])
  const dayList = getDays(params)
  const { data: shiftListResp, refresh } = useRequest(
    () => getAdvisorShiftList({ ...params, page: paginationModel.page + 1, size: paginationModel.pageSize }),
    {
      debounceWait: 500,
      cacheKey: `/schedule/list_${paginationModel.page}`,
      refreshDeps: [params, paginationModel]
    }
  )

  const { data: advisorListResp, loading } = useRequest(
    () => getAdvisorList({ page: paginationModel.page + 1, size: paginationModel.pageSize }),
    {
      debounceWait: 500,
      cacheKey: `/advisor/list_${paginationModel.page}`,
      refreshDeps: [paginationModel]
    }
  )

  useEffect(() => {
    if (!isUndefined(advisorListResp) && !isUndefined(shiftListResp) && advisorListResp?.page === shiftListResp?.page) {
      const advisorList = advisorListResp?.data ?? []
      const shiftList = shiftListResp?.data ?? []
      const extraAdvisors = differenceBy(advisorList, shiftList, 'advisor_id')
      const list = [...shiftList, ...extraAdvisors].map((item) => {
        const { daily_shifts = [] } = item
        return {
          id: item.id || item.advisor_id,
          ...item,
          ...mapValues(
            keyBy(dayList, (v: string) => v),
            (date: string) => find(daily_shifts, { date }) || {}
          )
        }
      })
      setRows(list)
    }
  }, [shiftListResp, advisorListResp])

  const columns = [
    {
      field: 'name',
      headerName: '职级 + 用户名',
      width: 180,
      renderCell: (record: GridRenderCellParams) => {
        const { row } = record
        return <NameGradeCell row={row} copyKey="advisor_id" />
      }
    },
    ...dayList.map((v: string) => ({
      field: v,
      renderHeader: () => {
        return <Typography color={isPassed(v) ? grey[500] : grey[900]}>{dayjs(v).format('MM-DD ddd')}</Typography>
      },
      width: 130,
      renderCell(record: GridRenderCellParams) {
        const { value, row, field } = record
        return <ScheduleActionButton field={field} value={value} row={row} refresh={refresh} />
      }
    })),
    {
      field: 'actions',
      headerName: '操作',
      width: 100,
      renderCell(record: GridRenderCellParams) {
        const { row } = record
        return (
          <MoreActionButton
            menuItems={[
              entries(pick(ButtonConfig, ['add'])).map(
                ([type, btn]: [type: 'add', btn: { label: string; icon: ElementType }]) => {
                  return (
                    <BatchScheduleButton
                      key={type}
                      type={type}
                      refresh={refresh}
                      row={row}
                      renderTrigger={(props) => (
                        <MenuItem {...props}>
                          <ListItemIcon>
                            <btn.icon size="1.2rem" />
                          </ListItemIcon>
                          <Typography variant="inherit">批量{btn.label}</Typography>
                        </MenuItem>
                      )}
                    />
                  )
                }
              )
            ]}
          />
        )
      }
    }
  ]

  return (
    <MainCard title={<DatePeriodSelect params={params} setParams={setParams} />}>
      <Grid container spacing={gridSpacing}>
        <Grid item xs={12} sx={{ minHeight: 500 }}>
          <DataGridPro
            loading={loading}
            rows={rows}
            columns={columns}
            editMode="cell"
            pagination
            pageSizeOptions={PageSizes}
            paginationModel={paginationModel}
            onPaginationModelChange={setPaginationModel}
            rowCount={advisorListResp?.total ?? DefaultPagination.pageSize}
            disableRowSelectionOnClick
            paginationMode="server"
            {...(matches && { pinnedColumns: { left: ['name'], right: ['actions'] } })}
          />
        </Grid>
      </Grid>
    </MainCard>
  )
}

export default Schedule

function getDays({ start_date, end_date }: { start_date: string; end_date: string }) {
  const startDate = dayjs(start_date)
  const endDate = dayjs(end_date)
  return range(0, endDate.diff(startDate, 'day') + 1).map((i: number) => startDate.add(i, 'day').format('YYYY-MM-DD'))
}
